package com.chexiehui.jc.ui.fragment;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.aries.ui.view.title.TitleBarView;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpFragment;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.entity.CommonToolsInfo;
import com.chexiehui.jc.entity.HomeActionInfo;
import com.chexiehui.jc.entity.MineStatisticInfo;
import com.chexiehui.jc.entity.UserInfo;
import com.chexiehui.jc.event.MerchantAuthSaveEvent;
import com.chexiehui.jc.event.MyCarInfoChangeEvent;
import com.chexiehui.jc.event.UserInfoChangeEvent;
import com.chexiehui.jc.mvp.mine.MineCovenant;
import com.chexiehui.jc.mvp.mine.MinePresenter;
import com.chexiehui.jc.ui.activity.AboutActivity;
import com.chexiehui.jc.ui.activity.BrowseHistoryActivity;
import com.chexiehui.jc.ui.activity.CarMerchantAuthActivity;
import com.chexiehui.jc.ui.activity.FeedBackActivity;
import com.chexiehui.jc.ui.activity.LoanQuotaCalculateActivity;
import com.chexiehui.jc.ui.activity.MessageListActivity;
import com.chexiehui.jc.ui.activity.MyCarEditActivity;
import com.chexiehui.jc.ui.activity.MyCarListActivity;
import com.chexiehui.jc.ui.activity.MyCollectionActivity;
import com.chexiehui.jc.ui.activity.MyFansListActivity;
import com.chexiehui.jc.ui.activity.MyFollowActivity;
import com.chexiehui.jc.ui.activity.MyForumListActivity;
import com.chexiehui.jc.ui.activity.MyInquiryListActivity;
import com.chexiehui.jc.ui.activity.MySendPostActivity;
import com.chexiehui.jc.ui.activity.SettingActivity;
import com.chexiehui.jc.ui.activity.UserInfoActivity;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.utils.SerializableSpTools;
import com.chexiehui.jc.widget.CircleImageView;
import com.chexiehui.jc.widget.NonSlidingGridView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: SongJun.
 * CreateDate: 2019/1/21 0021.
 * Description:
 */

public class MineFragment extends BaseMvpFragment<MinePresenter> implements MineCovenant.View {
    @BindView(R.id.titleBar)
    TitleBarView titleBar;
    @BindView(R.id.iv_user_avatar)
    CircleImageView ivUserAvatar;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.rtv_user_auth)
    RadiusTextView rtvUserAuth;
    @BindView(R.id.iv_right_setting)
    ImageView ivRightSetting;
    @BindView(R.id.rl_user_info_container)
    RelativeLayout rlUserInfoContainer;
    @BindView(R.id.nsgv_statistic_grid)
    NonSlidingGridView nsgvStatisticGrid;
    @BindView(R.id.nsgv_menu_action_grid)
    NonSlidingGridView nsgvMenuActionGrid;
    @BindView(R.id.nsgv_my_car_grid)
    NonSlidingGridView nsgvMyCarGrid;
    @BindView(R.id.tv_car_loan_quota_title)
    TextView tvCarLoanQuotaTitle;
    @BindView(R.id.tv_car_loan_quota)
    TextView tvCarLoanQuota;
    @BindView(R.id.tv_car_loan_quota_text)
    TextView tvCarLoanQuotaText;
    @BindView(R.id.tv_car_mortgage_quota_title)
    TextView tvCarMortgageQuotaTitle;
    @BindView(R.id.tv_car_mortgage_quota)
    TextView tvCarMortgageQuota;
    @BindView(R.id.nsgv_common_action_grid)
    NonSlidingGridView nsgvCommonActionGrid;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private UserInfo userInfo;
    private List<MineStatisticInfo> statisticData;
    private List<HomeActionInfo> actionData;
    private List<CommonToolsInfo> commonToolsData;
    private CommonAdapter<CommonToolsInfo> commonToolsAdapter;

    public static MineFragment getInstance() {
        MineFragment fragment = new MineFragment();
        return fragment;
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        userInfo = SerializableSpTools.getUserInfo();
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setEnableOverScrollDrag(true);
        refreshLayout.setDragRate(0.5f);
        refreshLayout.setOnRefreshListener(refreshLayout -> mvpPresenter.getUserInfo());

        commonToolsData = new ArrayList<>();
        commonToolsAdapter = new CommonAdapter<CommonToolsInfo>(mActivity, R.layout.item_mine_common_tools, commonToolsData) {
            @Override
            protected void convert(ViewHolder viewHolder, CommonToolsInfo item, int position) {
                viewHolder.setText(R.id.tv_item_label, item.getName());
                viewHolder.setImageResource(R.id.iv_item_icon, item.getIcon());
                RadiusTextView rtv_item_status = viewHolder.getView(R.id.rtv_item_status);
                if(item.getType() == 1){
                    rtv_item_status.setVisibility(View.VISIBLE);
                    rtv_item_status.setText(userInfo.getCarAuthStr());
                    if(userInfo.getCarAuth() == 0 || userInfo.getCarAuth() == 2){
                        rtv_item_status.getDelegate().setBackgroundColor(ContextCompat.getColor(mActivity, R.color.c_F44336)).init();
                    }else if(userInfo.getCarAuth() == 1){
                        rtv_item_status.getDelegate().setBackgroundColor(ContextCompat.getColor(mActivity, R.color.c_365EF0)).init();
                    }else{
                        rtv_item_status.setVisibility(View.GONE);
                    }
                }else{
                    rtv_item_status.setVisibility(View.GONE);
                }
            }
        };
        nsgvCommonActionGrid.setAdapter(commonToolsAdapter);
        nsgvCommonActionGrid.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            if (commonToolsData.get(position).getClz() != null) {
                startActivity(commonToolsData.get(position).getClz());
            }
        });
        setHeadInfo();
        setStatisticCountInfo();
        setMenuInfo();
        setMyCarInfo();
        setCommonToolsInfo();
    }

    @OnClick({R.id.iv_user_avatar, R.id.tv_user_name, R.id.tv_add_car, R.id.iv_right_setting, R.id.tv_car_loan_quota_text})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_user_avatar:
            case R.id.tv_user_name:
                startActivity(UserInfoActivity.class, new BundleBuilder().putString("userId", userInfo.getId()).create());
                break;
            case R.id.tv_add_car:
                startActivity(MyCarListActivity.class);
                break;
            case R.id.iv_right_setting:
                startActivity(SettingActivity.class);
                break;
            case R.id.tv_car_loan_quota_text:
                startActivity(LoanQuotaCalculateActivity.class);
                break;
        }
    }

    private void setCommonToolsInfo() {
        commonToolsData.clear();
//        commonToolsData.add(new CommonToolsInfo("浏览历史", R.mipmap.ic_cygn_llls));
//        commonToolsData.add(new CommonToolsInfo("我的论坛", R.mipmap.ic_cygn_wdlt));
//        commonToolsData.add(new CommonToolsInfo("车商认证", R.mipmap.ic_cygn_csrz));
//        commonToolsData.add(new CommonToolsInfo("媒体号认证", R.mipmap.ic_cygn_csrz));
        commonToolsData.add(new CommonToolsInfo("申请的论坛", R.mipmap.ic_sqdlt, MyForumListActivity.class));
        commonToolsData.add(new CommonToolsInfo("车商认证", R.mipmap.ic_cygn_csrz, 1, CarMerchantAuthActivity.class));
        commonToolsData.add(new CommonToolsInfo("用户反馈", R.mipmap.ic_cygn_yhfk, FeedBackActivity.class));
        commonToolsData.add(new CommonToolsInfo("关于车协汇", R.mipmap.ic_spsms, AboutActivity.class));
        commonToolsAdapter.notifyDataSetChanged();
    }

    private void setMyCarInfo() {
        if(userInfo.getCars().size() > 0){
            List<CarInfo> list = new ArrayList<>();
            for (int i = 0; i < userInfo.getCars().size(); i++) {
                if(i > 2){
                    break;
                }
                list.add(userInfo.getCars().get(i));
            }
            nsgvMyCarGrid.setAdapter(new CommonAdapter<CarInfo>(mActivity, R.layout.item_mine_my_car, list) {
                @Override
                protected void convert(ViewHolder viewHolder, CarInfo item, int position) {
                    GlideUtil.loadImageViewCrop(mActivity, item.getImg(), viewHolder.getView(R.id.iv_item_icon),
                            R.drawable.shape_square, R.drawable.shape_square);
                    viewHolder.setText(R.id.tv_item_name, item.getName());
                    viewHolder.getConvertView().setOnClickListener(new NoDoubleClickListener() {
                        @Override
                        public void onNoDoubleClick(View view) {
                            startActivity(MyCarEditActivity.class, new BundleBuilder().putSerializable("entity", item).create());
                        }
                    });
                }
            });
        }
    }

    private void setHeadInfo() {
        GlideUtil.loadImageViewCircleCrop(mActivity, userInfo.getPhoto(), ivUserAvatar,
                R.drawable.shape_circle, R.drawable.shape_circle);
        tvUserName.setText(userInfo.getName());
        rtvUserAuth.setVisibility(userInfo.isAuth() ? View.VISIBLE : View.GONE);
        tvCarLoanQuota.setText(userInfo.getCarLoanLimit() > 500000 ? "500000+" : userInfo.getCarLoanLimit() + "");
        tvCarMortgageQuota.setText(userInfo.getMortgageLimit() > 500000 ? "500000+" : userInfo.getMortgageLimit() + "");
    }

    private void setStatisticCountInfo() {
        statisticData = new ArrayList<>();
        // statisticData.add(new MineStatisticInfo("动态", userInfo.getPostCount()));
        statisticData.add(new MineStatisticInfo("关注", userInfo.getFollowCount(), MyFollowActivity.class));
        statisticData.add(new MineStatisticInfo("粉丝", userInfo.getFansCount(), MyFansListActivity.class));
        statisticData.add(new MineStatisticInfo("消息", userInfo.getNewsCount(), MessageListActivity.class));
        nsgvStatisticGrid.setNumColumns(statisticData.size());
        nsgvStatisticGrid.setAdapter(new CommonAdapter<MineStatisticInfo>(mActivity, R.layout.item_mine_statistic, statisticData) {
            @Override
            protected void convert(ViewHolder viewHolder, MineStatisticInfo item, int position) {
                viewHolder.setText(R.id.tv_item_count, item.getCount() + "");
                viewHolder.setText(R.id.tv_item_name, item.getTitle());
            }
        });
        nsgvStatisticGrid.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            if (statisticData.get(position).getClz() != null) {
                startActivity(statisticData.get(position).getClz());
            }
        });
    }

    private void setMenuInfo() {
        actionData = new ArrayList<>();
        actionData.add(new HomeActionInfo("浏览历史", R.mipmap.ic_mine_lljl, BrowseHistoryActivity.class));
        actionData.add(new HomeActionInfo("收藏", R.mipmap.ic_mine_wdsc, MyCollectionActivity.class));
        actionData.add(new HomeActionInfo("发布", R.mipmap.ic_mine_fbjl, MySendPostActivity.class));
        actionData.add(new HomeActionInfo("询价", R.mipmap.ic_mine_xjjl, MyInquiryListActivity.class));
        nsgvMenuActionGrid.setAdapter(new CommonAdapter<HomeActionInfo>(mActivity, R.layout.item_mine_menu_action, actionData) {
            @Override
            protected void convert(ViewHolder viewHolder, HomeActionInfo item, int position) {
                viewHolder.setText(R.id.tv_item_label, item.getName());
                viewHolder.setImageResource(R.id.iv_item_icon, item.getIcon());
            }
        });
        nsgvMenuActionGrid.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            if (actionData.get(position).getClz() != null) {
                startActivity(actionData.get(position).getClz());
            }
        });
    }

    @Override
    protected MinePresenter createPresenter() {
        return new MinePresenter(this);
    }

    @Override
    public void onGetUserInfoSuccess(BaseModel<UserInfo> successResult) {
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(true);
        }
        userInfo = successResult.getData();
        SerializableSpTools.putUserInfo(userInfo);
        setHeadInfo();
        setMyCarInfo();
        setStatisticCountInfo();
        setCommonToolsInfo();
    }

    @Override
    public void onGetUserInfoFailure(BaseModel<Object> failureResult) {
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(false);
        }
    }

    @Subscribe
    public void onMyCarInfoChangeEvent(MyCarInfoChangeEvent event) {
        mvpPresenter.getUserInfo();
    }

    @Subscribe
    public void onMyCarInfoChangeEvent(MerchantAuthSaveEvent event) {
        mvpPresenter.getUserInfo();
    }

    @Subscribe
    public void onUserInfoChangeEvent(UserInfoChangeEvent event) {
        userInfo = SerializableSpTools.getUserInfo();
        setHeadInfo();
    }
}
